//
//  LDLoginBaseVC.swift
//  DingDongZP
//
//  Created by 三秒文化 on 16/6/27.
//  Copyright © 2016年 51ledian.com. All rights reserved.
//

import UIKit
import ReactiveCocoa

class LDLoginBaseVC: UIViewController {
    
    
    var headImgView:UIImageView!
    var phoneTextField:UITextField!
    var passwordTextField:UITextField!
    var securityCodeTextField:UITextField!
    var enterBtn:UIButton!
    var getcodeBtn:UIButton!
    var timer:NSTimer?
    
    let headImgView_Y:CGFloat = IPHONE4S ? 0:(IPHONE6UP ? 100:80)
    let headImgView_height:CGFloat = IPHONE4S ? 0:120
    let phoneTextfieldTopOffset:CGFloat = IPHONE4S ? 100:50
    
    let passwordtag = 566
    let securitytag = 567
    
    override func viewWillAppear(animated: Bool) {
        
        navigationController?.navigationBarHidden = true
        UIApplication.sharedApplication().statusBarStyle = .Default
    }
    
    override func viewWillDisappear(animated: Bool) {
        
        navigationController?.navigationBarHidden = false
        UIApplication.sharedApplication().statusBarStyle = .LightContent
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let backButton:UIButton = UIButton(type:.Custom)
        
        backButton.frame = CGRectMake(15, 35, 35, 35)
        backButton.layer.cornerRadius = 35/2
        backButton.setBackgroundImage(UIImage(named: "返回back"), forState: UIControlState.Normal)
        view.addSubview(backButton)
        
        backButton.bk_whenTapped { [weak self] in
            
            self!.backAction()
        }
        
        setupDefaultContent()
        setupSignal()
        tapView()
    }
    
    func backAction(){
        
        navigationController?.popViewControllerAnimated(true)
    }
    
    func setupSignal() {
        
        //init phone
        let phoneNumSignal = phoneTextField.rac_textSignal().map { [weak self] (obj) -> AnyObject! in
            
            let textStr = obj as? String ?? ""
            var rangStr:String?
            
            if textStr.characters.count >= 11 {
                
                let range = textStr.startIndex.advancedBy(11)
                rangStr = textStr.substringToIndex(range)
                self?.phoneTextField.text = rangStr
                
                return true
            } else {
                
                return self?.validPhoneNum(textStr)
            }
        }
        
        //password
        let passwordSignal = passwordTextField.rac_textSignal().map { [weak self] (obj) -> AnyObject! in
            
            let textStr = obj as? String ?? ""
            return self?.validPassword(textStr)
        }
        
        //code
        let codeSignal = securityCodeTextField.rac_textSignal().map { (obj) -> AnyObject! in
            
            let textStr = obj as? String ?? ""
            return textStr.characters.count > 0 ? true:false  //self?.validPassword(textStr)
        }
        
        let getCodeSignal = RACSignal.combineLatest([phoneNumSignal,passwordSignal]).map({ (obj) -> AnyObject! in
            
            let tuple = obj as? RACTuple ?? RACTuple()
            
            let aa = tuple.first as? Bool ?? false
            return aa
            
        })
        
        let loginSignal = RACSignal.combineLatest([phoneNumSignal,passwordSignal,codeSignal]).map {
            [weak self](obj) -> AnyObject! in
            
            let tuple = obj as? RACTuple ?? RACTuple()
            
            let aa = tuple.first as? Bool ?? false
            let bb = tuple.second as? Bool ?? false
            let cc = tuple.third as? Bool ?? false
            
            if self?.passwordTextField.hidden == true {
                
                return (aa && cc)
            } else {
                return (aa && bb && cc)
            }
            
        }
        
        //通过signal 返回 验证码状态
        RAC(getcodeBtn,"enabled") <~ getCodeSignal.map({ [weak self] (obj) -> AnyObject! in
            
            let able = obj as? Bool
            
            if able == true {
                
                self!.getcodeBtn.backgroundColor = LDGolbalColor.Green
                self?.getcodeBtn.userInteractionEnabled = true
                return true
            } else  {
                
                self!.getcodeBtn.backgroundColor = LDIconColor.LightGray
                self?.getcodeBtn.userInteractionEnabled = false
                return false
            }
            
            })
        
        
        //通过signal 返回 登录按钮状态
        RAC(enterBtn,"backgroundColor") <~ loginSignal.map({ [weak self] (obj) -> AnyObject! in
            
            let able = obj as? Bool
            
            if able == true {
                
                self?.enterBtn.enabled = true
                return LDGolbalColor.Green
            } else  {
                
                self?.enterBtn.enabled = false
                return LDIconColor.LightGray
            }
            
            })
        
        
        //监听键盘
        NSNotificationCenter.defaultCenter().rac_addObserverForName(UIKeyboardWillShowNotification, object: nil)
            .subscribeNext { [weak self](obj) in
                
                guard let noti = obj as? NSNotification else {
                    
                    return
                }
                self?.keyboardShow(noti)
        }
        
        //监听键盘辞去
        NSNotificationCenter.defaultCenter().rac_addObserverForName(UIKeyboardWillHideNotification, object: nil).subscribeNext
            { [weak self] (obj) in
                
                NSOperationQueue.mainQueue().addOperationWithBlock({
                    self?.keyboardHidden(nil)
                })
                
        }
        
    }
    //
    func keyboardShow(noti:NSNotification) {
        
        let userinfo = noti.userInfo
        let value = userinfo!["UIKeyboardFrameEndUserInfoKey"]
        let height = value?.CGRectValue().height ?? 0
        debugPrint(height)
        
        
        
//        UIView.animateWithDuration(0.5) { [weak self] in
//            
//            
//            self?.view.frame = CGRectMake(0, -120, LDFrame.ScreenWidth, LDFrame.ScreenHeight)
//        }
    }
    //
    func keyboardHidden(noti:NSNotification?) {
        
        
//        UIView.animateWithDuration(0.3) { [weak self] in
//            
//            self?.view.frame = CGRectMake(0, 0, LDFrame.ScreenWidth, LDFrame.ScreenHeight)
//        }
    }
    
    func tapView() {
        
        //辞去键盘
        let tap = UITapGestureRecognizer()
        tap.rac_gestureSignal().subscribeNext { [weak self](obj) in
            
            self?.phoneTextField.resignFirstResponder()  //endEditing(true)
            self?.passwordTextField.endEditing(true)
            self?.securityCodeTextField.endEditing(true)
        }
        view.userInteractionEnabled = true
        view.addGestureRecognizer(tap)
        
    }
    
    //登录
    func enterClick() {
        
        
    }
    
    //验证手机号
    func validPhoneNum(phone:String) -> Bool{
        
        
        if phone.characters.count == 11 {
            
            return true
        } else {
            return false
        }
    }
    
    //验证密码长度
    func validPassword(security:String) -> Bool{
        
        if security.characters.count < 6 {
            
            return false
        } else {
            
            return true
        }
    }
    
    //点击右边按钮操作
    func changStatus(btn:UIButton) {
        
    }
    //
    func requestCodeNet() {
        
        let phone = phoneTextField.text ?? ""
        var countMax:NSTimeInterval = 60
        
        LDCheckPublicInfo.shareInstance.getSecurityCode(phone, succ: { [weak self] in
            LDShowHUB.shareInstance.showBarStatus("验证码已发送")
            
            self?.timer = NSTimer.bk_scheduledTimerWithTimeInterval(1, block: { (time) in
                
                countMax -= 1
                self?.timeCountDown(countMax)
                
                }, repeats: true)
            
            
        }) { [weak self] (data) in
            
            let notice = data as? String ?? "验证码发送失败"
            LDShowHUB.shareInstance.showBarStatus(notice)
            self?.getcodeBtn.userInteractionEnabled = true
        }
    }
    
    //倒计时
    func timeCountDown(time:NSTimeInterval) {
        
        if time == 0 {
            
            getcodeBtn.userInteractionEnabled = true
            getcodeBtn.setTitle("获取", forState: .Normal)
            self.timer?.invalidate()
            
        } else {
            
            getcodeBtn.userInteractionEnabled = false
            getcodeBtn.setTitle("\(Int(time))秒", forState: UIControlState.Normal)
        }
    }
}

extension LDLoginBaseVC:UITextFieldDelegate {
    
    //布局
    func setupDefaultContent() {
        
        navigationController?.navigationBar.translucent = false
        //        navigationController?.navigationBar.opaque = true
        
        view.backgroundColor = LDGolbalColor.BgGoundGray
        view.frame = CGRectMake(0, 0, LDFrame.ScreenWidth, LDFrame.ScreenHeight)
        
        headImgView = UIImageView(image: UIImage.init(named: "LOGO"))
        headImgView.frame = CGRectMake(0, headImgView_Y, 90, headImgView_height)
        headImgView.center.x = LDFrame.ScreenWidth/2
        
        phoneTextField = UITextField()
        phoneTextField.keyboardType = .NumberPad
        
        passwordTextField = UITextField()
        passwordTextField.leftView = UIImageView(image: UIImage(named: "密码"))
        passwordTextField.secureTextEntry = true
        
        securityCodeTextField = UITextField()
        securityCodeTextField.keyboardType = .NumberPad
        
        //获取验证码按钮
        getcodeBtn = UIButton.setDetailsBtn("获取", picName: nil, btnBackColor: nil, titleColor: LDFontColor.White)!
        getcodeBtn.tag = securitytag
        getcodeBtn.backgroundColor = LDIconColor.LightGray
        getcodeBtn.titleLabel?.font = LDFont.Font12
        
        getcodeBtn.bk_whenTapped({ [weak self] in
            
            self?.changStatus(self!.getcodeBtn)
            self!.getcodeBtn.selected = !self!.getcodeBtn.selected
            
            })
        
        // 确定按钮
        enterBtn = UIButton.setDetailsBtn("按钮", picName: nil, btnBackColor: LDGolbalColor.Green, titleColor: LDGolbalColor.White)
        
        enterBtn.bk_whenTapped { [weak self] in
            self?.enterClick()
        }
        
        setTextFieldPic("phone",selImg: nil, isLift: true, fieldName: phoneTextField,placeHold: "请输入注册的手机号码",tag: nil)
        
        setTextFieldPic("password", selImg: nil, isLift: true, fieldName: passwordTextField,placeHold: "请输入新的用户密码",tag: nil)
        setTextFieldPic("password_close", selImg: "password_open", isLift: false, fieldName: passwordTextField, placeHold: nil,tag:passwordtag)
        setTextFieldPic("验证码", selImg: nil , isLift: true, fieldName: securityCodeTextField,placeHold: "验证码",tag: nil)
        
        
        view.addSubview(headImgView)
        view.addSubview(phoneTextField)
        view.addSubview(passwordTextField)
        view.addSubview(securityCodeTextField)
        view.addSubview(getcodeBtn)
        view.addSubview(enterBtn)
        
        
        phoneTextField.snp_makeConstraints { (make) in
            
            make.top.equalTo(headImgView.snp_bottom).offset(phoneTextfieldTopOffset)
            make.left.equalTo(25)
            make.right.equalTo(-25)
            make.height.equalTo(48)
        }
        
        passwordTextField.snp_makeConstraints { (make) in
            
            make.top.equalTo(phoneTextField.snp_bottom).offset(15)
            make.left.equalTo(25)
            make.right.equalTo(-25)
            make.height.equalTo(48)
        }
        
        securityCodeTextField.snp_makeConstraints { (make) in
            
            make.top.equalTo(passwordTextField.snp_bottom).offset(15)
            make.left.height.equalTo(phoneTextField)
            make.right.equalTo(phoneTextField).offset(-70)
        }
        
        getcodeBtn.snp_makeConstraints { (make) in
            
            make.top.equalTo(securityCodeTextField.snp_top)
            make.left.equalTo(securityCodeTextField.snp_right).offset(10)
            make.right.equalTo(passwordTextField.snp_right)
            make.height.equalTo(securityCodeTextField.snp_height)
        }
        
        enterBtn.snp_makeConstraints { (make) in
            
            make.top.equalTo(securityCodeTextField.snp_bottom).offset(40)
            make.left.right.height.equalTo(phoneTextField)
        }
    }
    
    /* 添加左右textFieldView */
    func setTextFieldPic(norImg:String,selImg:String?, isLift:Bool,fieldName:UITextField,placeHold:String?,tag:Int?) {
        
        let imageV = UIImageView(image: UIImage(named: norImg))
        
        fieldName.borderStyle = UITextBorderStyle.RoundedRect
        fieldName.delegate = self
        fieldName.font = UIFont.systemFontOfSize(15)
        fieldName.backgroundColor = LDGolbalColor.White
        
        if placeHold != nil {
            fieldName.placeholder = placeHold ?? ""
        }
        
        if isLift{
            
            fieldName.leftView = imageV
            fieldName.leftViewMode = .Always
        }
        else{
            
            var btn = UIButton()
            
            if tag != nil {
                
                btn.tag = tag!
            }
            
            //自定义button
            if btn.tag == securitytag {
                
                btn = UIButton.setDetailsBtn("获取验证码", picName: nil, btnBackColor: nil, titleColor: LDFontColor.Green)!
                btn.tag = securitytag
                btn.titleLabel?.font = LDFont.Font12
                getcodeBtn = btn
            }
            //
            
            let norimage = UIImage(named: norImg)
            
            var selimage:UIImage? = nil
            
            if selImg != nil {
                
                selimage = UIImage(named: selImg!)
                btn.setBackgroundImage(selimage, forState: UIControlState.Normal)
            }
            
            
            btn.setBackgroundImage(norimage, forState: UIControlState.Normal)
            
            
            btn.frame.size = (norimage?.size)!
            fieldName.rightView = btn
            
            fieldName.rightViewMode = .Always
            
            btn.bk_whenTapped({ [weak self] in
                
                
                self?.changStatus(btn)
                btn.selected = !btn.selected
                
                if btn.selected == false {
                    
                    btn.setBackgroundImage(norimage, forState: UIControlState.Normal)
                    
                } else {
                    
                    guard selimage == nil else {
                        
                        btn.setBackgroundImage(selimage, forState: UIControlState.Normal)
                        return
                    }
                }
                
                })
        }
        
    }
}
